//
//  CategoryPickerViewController.swift
//  MyLocations
//
//  Created by cygarm on 15/12/8.
//  Copyright © 2015年 cygarm. All rights reserved.
//

import UIKit

class CategoryPickerViewController: UITableViewController {
	
	var selectedCategoryName = ""
	var selectedCategoryIndex: NSIndexPath?
	let categories = [
		"No Category",
		"Apple Store",
		"Bar",
		"Bookstore",
		"BeiJing",
		"Club",
		"Grocery Store",
		"Historic Building",
		"House",
		"Icecream Vendor",
		"Landmark",
		"Park"]
	
	override func viewDidLoad() {
		super.viewDidLoad()
		
		tableView.backgroundColor = UIColor.blackColor()
		tableView.separatorColor = UIColor(white: 1.0, alpha: 0.2)
		tableView.indicatorStyle = .White
	}

	//MARK: UITableViewDelegate
	override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {		
		if let oldIndex = selectedCategoryIndex {
			if let oldCell = tableView.cellForRowAtIndexPath(oldIndex) {
				oldCell.accessoryType = .None
			}
		}
		if let newCell = tableView.cellForRowAtIndexPath(indexPath) {
			newCell.accessoryType = .Checkmark
		}
		selectedCategoryIndex = indexPath
		selectedCategoryName = categories[selectedCategoryIndex!.row]
	}
	
	override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
		cell.backgroundColor = UIColor.blackColor()
		
		if let textLabel = cell.textLabel {
			textLabel.textColor = UIColor.whiteColor()
			textLabel.highlightedTextColor = textLabel.textColor
		}
		
		let selectionView = UIView(frame: CGRect.zero)
		selectionView.backgroundColor = UIColor(white: 1.0, alpha: 0.2)
		cell.selectedBackgroundView = selectionView
	}
	
	//MARK: UITableViewDataSource
	override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
		return 1
	}
	
	override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
		return categories.count
	}
	
	override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
		let cell = tableView.dequeueReusableCellWithIdentifier("CategoryCell")!
		cell.textLabel?.text = categories[indexPath.row]
		
		if cell.textLabel?.text == selectedCategoryName {
			cell.accessoryType = .Checkmark
			selectedCategoryIndex = indexPath
		} else {
			cell.accessoryType = .None
		}
		
		return cell
	}
	
	
	//MARK: IBAction
	
	//MARK: Segue handle
	override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
		if segue.identifier == "UnwindSegueCategoryPicked" {
			let cell = sender as! UITableViewCell
			if let indexPath = tableView.indexPathForCell(cell) {
				selectedCategoryName = categories[indexPath.row]
			}
		}
	}
}
